package org.huangjiahui.rpc.transport.netty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.huangjiahui.rpc.entity.RpcRequest;
import org.huangjiahui.rpc.entity.RpcResponse;
import org.huangjiahui.rpc.enumeration.RpcError;
import org.huangjiahui.rpc.exception.RpcException;
import org.huangjiahui.rpc.factory.SingletonFactory;
import org.huangjiahui.rpc.loadbalancer.LoadBalancer;
import org.huangjiahui.rpc.loadbalancer.RandomLoadBalancer;
import org.huangjiahui.rpc.registry.NacosServiceDiscovery;
import org.huangjiahui.rpc.registry.ServiceDiscovery;
import org.huangjiahui.rpc.serializer.CommonSerializer;
import org.huangjiahui.rpc.transport.RpcClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.util.concurrent.CompletableFuture;

/**
 * @author huangjiahui
 */
public class NettyClient implements RpcClient {

    private static final Logger logger = LoggerFactory.getLogger(NettyClient.class);
    private static final EventLoopGroup group;
    private static final Bootstrap bootstrap;

    static {
        group = new NioEventLoopGroup();
        bootstrap = new Bootstrap();
        bootstrap.group(group).channel(NioSocketChannel.class);
    }

    private final ServiceDiscovery serviceDiscovery;
    private final CommonSerializer serializer;

    private final UnprocessedRequests unprocessedRequests;

    public NettyClient(Integer serializer){this(DEFAULT_SERIALIZER, new RandomLoadBalancer());}
    public NettyClient(Integer serializer, LoadBalancer loadBalancer){
        this.serviceDiscovery = new NacosServiceDiscovery(loadBalancer);
        this.serializer = CommonSerializer.getByCode(serializer);
        this.unprocessedRequests = SingletonFactory.getInstance(UnprocessedRequests.class);
    }

    @Override
    public CompletableFuture<RpcResponse> sendRequest(RpcRequest rpcRequest) {
        if(serializer==null){
            logger.error("未设置序列化器");
            throw new RpcException(RpcError.SERVICE_NOT_FOUND);
        }
        CompletableFuture<RpcResponse> resultFuture = new CompletableFuture<>();
        try {
            InetSocketAddress inetSocketAddress = serviceDiscovery.lookupService(rpcRequest.getInterfaceName());
            ChannelProvider.get(inetSocketAddress,serializer);
        }catch (InterruptedException e){

        }
    }
}
